package de.wbh.gwt.form.layouter.shared.activity;

import java.util.List;

import javax.inject.Inject;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.inject.client.AsyncProvider;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

import de.wbh.gwt.form.layouter.gwt.rpc.ConfigurationServiceAsync;
import de.wbh.gwt.form.layouter.shared.Configuration;
import de.wbh.gwt.form.layouter.shared.place.EditPlace;

public class LoadConfigurationActivity extends AbstractActivity implements LoadConfigurationView.Presenter {

	private final AsyncProvider<LoadConfigurationView> viewProvider;
	private final PlaceController placeController;
	private final ConfigurationServiceAsync configurationService;

	private LoadConfigurationView view;

	@Inject
	public LoadConfigurationActivity(AsyncProvider<LoadConfigurationView> viewProvider, PlaceController placeController, ConfigurationServiceAsync configurationService) {
		this.viewProvider = viewProvider;
		this.placeController = placeController;
		this.configurationService = configurationService;
	}

	@Override
	public void configurationSelected(String conigurationId) {
		this.configurationService.getConf(conigurationId, new AsyncCallback<Configuration>() {
			@Override
			public void onFailure(Throwable caught) {
				caught.printStackTrace();
			}

			@Override
			public void onSuccess(Configuration result) {
				LoadConfigurationActivity.this.placeController.goTo(new EditPlace(result.efdName, result.pdfName, result.name));
			}
		});
	}

	@Override
	public void start(final AcceptsOneWidget panel, EventBus eventBus) {
		this.viewProvider.get(new AsyncCallback<LoadConfigurationView>() {

			@Override
			public void onFailure(Throwable caught) {
				caught.printStackTrace();
			}

			@Override
			public void onSuccess(LoadConfigurationView result) {
				LoadConfigurationActivity.this.view = result;
				LoadConfigurationActivity.this.view.setPresenter(LoadConfigurationActivity.this);
				panel.setWidget(LoadConfigurationActivity.this.view);

				LoadConfigurationActivity.this.configurationService.getConfs(new AsyncCallback<List<String>>() {

					@Override
					public void onFailure(Throwable caught) {
						//
					}

					@Override
					public void onSuccess(List<String> configs) {
						LoadConfigurationActivity.this.view.showConfigurations(configs);
					}
				});

				// Iterable<String> configs = Iterables.transform(Ranges.closed(0, 12).asSet(DiscreteDomains.integers()), new Function<Integer, String>() {
				// @Override
				// public String apply(Integer input) {
				// return "Konfiguration " + input;
				// }
				// });

			}
		});

	}

}
